'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
  //event为客户端上传的参数
 const fs = require("fs");
 const collection = db.collection('products');
 const users= db.collection('users');
  //console.log('event : ' + event)
  let list=[];
  for(let i=0; i<event.imgs.length; i++){
	  let path="product_imgs/"+event.product_id+i.toString()+".jpg";
	  list.push(path);
	  let src=event.imgs[i];
	 let result = await uniCloud.uploadFile({
		 cloudPath: path,
		 fileContent: new Buffer(src, 'base64')
	 });
  }
  let product={
		"product_id":event.product_id,
		"product_title":event.product_title,
		"product_content":event.product_content,
		"price":event.price,
		"raw_price":event.raw_price,
		"address":event.address,
		"phone":event.phone,
		"imgs":list,
		"classify":event.classify,
		"fresh_degree":event.fresh_degree,
		"trade_types":event.trade_types,
		"time":event.time,
		"user_name":event.user_name,
		"user_id":event.user_id,
		"icon":event.icon,
		"is_persuaded":false,
		"is_finished":false,
		"view_count":0,
		"comments":[],
		"buyer_id":"",
		"buyer_name":"",
		"buyer_icon":""
  }
	let res=await collection.add(product);
	res=await users.doc(event.user_id).get();
	list=res.data[0].my_sales;
	list.push(event.product_id);
	res=await users.doc(event.user_id).update({
		my_sales:list
	})
  //返回数据给客户端
  return {"status":2}
};
